package com.study.springbootsecurity.service.impl;

import com.study.springbootsecurity.constants.JwtTokenConstants;
import com.study.springbootsecurity.service.AccessTokenBlackService;
import com.study.springbootsecurity.util.DeviceFinerUtil;
import com.study.springbootsecurity.util.RedisCache;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO 访问令牌黑名单业务接口
 * @author: Huangjianyun
 * @date: 2025-06-11 4:12
 */
@Service
public class AccessTokenBlackServiceImpl implements AccessTokenBlackService {
    @Autowired
    private RedisCache redisCache;

    @Override
    public void addToBlacklist(String deviceFingerprint, String username, String accessToken, Long timeout) {
        // 构造黑名单key
        // 获取客户端设备标识 黑名单和客户端标识绑定
        String blockKey = JwtTokenConstants.BLACK_LIST_REDIS_KEY_PREFIX+username+":"+deviceFingerprint;
        redisCache.set(blockKey,accessToken,timeout, TimeUnit.MILLISECONDS);
    }

    @Override
    public boolean isBlacklisted(String deviceFingerprint, String username,String accessToken) {
        String blockKey = JwtTokenConstants.BLACK_LIST_REDIS_KEY_PREFIX+username+":"+deviceFingerprint;

        if (redisCache.hasKey(blockKey) &&  StringUtils.equals(accessToken,redisCache.getCacheObject(blockKey))){
            return true;
        }
        return false;
    }

}
